<template>
    <div>
        <div>
            <el-form :inline="true" size="mini">
                <el-form-item label="标题">
                    <el-input v-model="search.title" size="mini" style="width:130px;"></el-input>
                </el-form-item>
                <el-form-item>
                    <div>
                        <el-button type="primary" @click="onLoad">搜索</el-button>
                        <el-button type="success" @click="addDialog = true">添加</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table :data="data" border style="width: 100%">
                <el-table-column type="index" label="#" width="50" align="center"></el-table-column>
                <el-table-column prop="title" label="标题" width="220" align="center"></el-table-column>
                <el-table-column label="简介" align="center">
                    <template slot-scope="scope">
                        <p style="text-align: left;" v-if="scope.row.information" v-html="scope.row.information.substring(0,15)"></p>
                    </template>
                </el-table-column>
                <el-table-column label="封面" align="center" width="100">
                    <template slot-scope="scope">
                        <div>
                            <img v-if="scope.row.url" :src="config.api+scope.row.url" alt="" style="width: 30px; height: 30px; margin-top: 3px; margin-bottom: -4px;">
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="frequency" label="最大提交次数" width="120" align="center"></el-table-column>
                <el-table-column prop="create_time" label="提交时间" width="180" align="center"></el-table-column>
                <el-table-column label="操作" width="320px" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="editDialog = true;editForm = scope.row" size="mini">编辑</el-button>
                        <el-button type="success" @click="onCopy(scope.row)" size="mini">复制</el-button>
                        <el-button type="warning" @click="onLookMessage(scope.row)" size="mini">查看留言</el-button>
                        <el-button type="danger" @click="onDel(scope.row)" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right;margin: 15px auto;">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="p"
                    :page-sizes="[10,15,20, 30, 40]"
                    :page-size="limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"></el-pagination>
            </div>
        </div>
        <el-dialog title="添加活动" :visible.sync="addDialog" width="800px">
            <div style="max-height: 60vh;overflow: auto;padding-right: 30px;">
                <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px" size="small">
                    <el-form-item label="活动名称" prop="title">
                        <el-input v-model="addForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="活动简介" prop="information">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" resize="none" v-model="addForm.information"></el-input>
                    </el-form-item>
                    <el-form-item label="提交次数" prop="frequency">
                        <el-input v-model="addForm.frequency" @change="toInteger(false)"></el-input>
                    </el-form-item>
                    <el-form-item label="封面">
                        <el-upload class="avatar-uploader" :action="config.api+'/upload'" :show-file-list="false" 
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="addForm.url" :src="config.api+addForm.url" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="内容">
                        <div>
                            <quill-editor v-model="addForm.text" ref="quill" :options="options"></quill-editor>
                            <el-upload class="text-uploader" :action="config.api+'/upload'" :show-file-list="false" 
                            :on-success="handleTextSuccess" :before-upload="beforeAvatarUpload"></el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item align="right">
                        <el-button @click="addDialog = false">取消</el-button>
                        <el-button type="primary" @click="onAdd">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <el-dialog title="编辑活动" :visible.sync="editDialog" width="800px">
            <div style="max-height: 60vh;overflow: auto;padding-right: 30px;">
                <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px" size="small">
                    <el-form-item label="活动名称" prop="title">
                        <el-input v-model="editForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="活动简介" prop="information">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" resize="none" v-model="editForm.information"></el-input>
                    </el-form-item>
                    <el-form-item label="提交次数" prop="frequency">
                        <el-input v-model="editForm.frequency" @change="toInteger(true)"></el-input>
                    </el-form-item>
                    <el-form-item label="封面">
                        <el-upload class="avatar-uploader" :action="config.api+'/upload'" :show-file-list="false" 
                        :on-success="handleEditSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="editForm.url" :src="config.api+editForm.url" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="内容">
                        <div>
                            <quill-editor v-model="editForm.text" ref="quillEditor" :options="editOptions"></quill-editor>
                            <el-upload class="edit-text-uploader" :action="config.api+'/upload'" :show-file-list="false" 
                            :on-success="handleEditTextSuccess" :before-upload="beforeAvatarUpload"></el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item align="right">
                        <el-button @click="editDialog = false">取消</el-button>
                        <el-button type="primary" @click="onEdit">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {axget,axpost} from '@/components/api/index'
import api from '@/components/api/config'
// import VueClipboard from 'vue-clipboard2'
// VueClipboard.config.autoSetContainer = true
export default {
    data(){
        return {
            loading: false,
            data: [],
            total: 0,
            p:1,
            limit: 15,
            search: {
                title: ''
            },
            config: api,
            options: {
                modules:{
                    toolbar:{
                        container: [
                            [
                                'bold', 'italic', 'underline', 'strike',{ 'color': [] }, { 'background': [] },
                                { 'align': [] },'clean',{ 'list': 'bullet' },'code-block','link','image'
                            ]
                        ],
                        handlers:{
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.text-uploader input').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },

            editOptions: {
                modules:{
                    toolbar:{
                        container: [
                            [
                                'bold', 'italic', 'underline', 'strike',{ 'color': [] }, { 'background': [] },
                                { 'align': [] },'clean',{ 'list': 'bullet' },'code-block','link','image'
                            ]
                        ],
                        handlers:{
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.edit-text-uploader input').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },

            rules: {
                title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
                information: [{ required: true, message: '请输入活动简介', trigger: 'blur' }],
                frequency: [{ required: true, message: '请输入最大提交次数', trigger: 'blur' }]
            },
            addDialog: false,
            addForm: {
                title: '',
                information: '',
                frequency: 3,
                url: '',
                text: ''
            },
            editDialog: false,
            editForm: {},
            user: localStorage.getItem('user_id')
        }
    },
    created(){
        this.onLoad()
    },
    computed:{
        text(){
            return '123'
        }
    },
    methods:{
        onLoad(){
            this.loading = true
            let where = {
                p: this.p,
                limit: this.limit,
                search: this.search
            }
            axpost('/activity/getList',where).then(res=>{
                let data = res.data
                if(res.status === 200 && data.status === 200){
                    this.data = data.result.list
                    this.total = data.result.total
                }else{
                    this.$notify({title:'提示',message:'数据获取超时',type:"warning"})
                }
                this.loading = false
            })
        },
        onAdd(){
            this.$refs.addForm.validate((valid) => {
                let param = this.addForm
                param.u_id = this.user
                if(valid){
                    axpost('/activity/add',param).then(res => {
                        let data = res.data
                        if(res.status === 200 && data.status === 200){
                            this.$message.success('添加成功')
                            this.$refs.addForm.resetFields()
                            this.addForm.frequency = 3
                            this.addForm.text = ''
                            this.addDialog = false
                            this.onLoad()
                        }else{
                            this.$message.warning(data.message ? data.message : '添加失败')
                        }
                    })
                }
            })
        },
        onEdit(){
            this.$refs.editForm.validate((valid) => {
                let param = this.editForm
                param.u_id = this.user
                if(valid){
                    axpost('/activity/modify',param).then(res => {
                        let data = res.data
                        if(res.status === 200 && data.status === 200){
                            this.$message.success('编辑成功')
                            this.editDialog = false
                            this.onLoad()
                        }else{
                            this.$message.warning(data.message ? data.message : '编辑失败')
                        }
                    })
                }
            })
        },
        onLookMessage(row){
            this.$router.push('/activity/report/'+row.id)
        },
        onCopy(row){
            this.$alert( this.config.api + '/form/' + row.link, '复制链接', {
                confirmButtonText: '确定',
                callback: action => {}
            })
        },
        onDel(row){
            this.$confirm('确认删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                axpost('/activity/remove',{id:row.id}).then(res => {
                    let data = res.data
                    if(res.status === 200 && data.status === 200){
                        this.$message.success('删除成功')
                        this.onLoad()
                    }else{
                        this.$message.warning('删除失败')
                    }
                    this.loading = false
                })
            }).catch(r=>{})
        },
        toInteger(isEdit = false){
            if(isEdit){
                let fre = parseInt(this.editForm.frequency)
                this.editForm.frequency = isNaN(fre) ? '' : fre
            }else{
                let fre = parseInt(this.addForm.frequency)
                this.addForm.frequency = isNaN(fre) ? '' : fre
            }
        },
        handleTextSuccess(res,file){
            let quill = this.$refs.quill.quill
            if(res.status === 200){
                let length = quill.getSelection().index;
                quill.insertEmbed(length, 'image', this.config.api+res.result.url)
            }
        },
        handleEditTextSuccess(res,file){
            let quill = this.$refs.quillEditor.quill
            if(res.status === 200){
                let length = quill.getSelection().index;
                quill.insertEmbed(length, 'image', this.config.api+res.result.url)
            }
        },
        handleAvatarSuccess(res, file) {
            if(res.status === 200){
                this.addForm.url = res.result.url
            }
        },
        handleEditSuccess(res, file) {
            if(res.status === 200){
                this.editForm.url = res.result.url
            }
        },
        beforeAvatarUpload(file) {
            // console.log(file.type)
            let isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
            let isLt2M = file.size / 1024 / 1024 < 20;

            if (!isJPG) {
            this.$message.error('图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('图片大小不能超过 20MB!');
            }
            return isJPG && isLt2M;
        },
        handleCurrentChange(val){
            this.p = val
            this.onLoad()
        },
        handleSizeChange(val){
            this.limit = val
            this.onLoad()
        }
    }
}
</script>

<style lang="scss" scoped>
.avatar-uploader{
    width: 60px;
    height: 60px;
    .avatar-uploader-icon{
        text-align: center;
        width: 60px;
        height: 60px;
        font-size: 28px;
        line-height: 60px;
    }
    .avatar{
        border-radius: 5px;
    }
}
</style>